/**
 * 
 */
package fr.cephb.swing;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.TableModel;

/**
 * @author operon
 * An action used tio save the content of a JTable to a file
 *
 */
public class ActionSaveTableAs
	extends AbstractAction
	{
	private static final long serialVersionUID = 1L;
	private JTable table=null;
	private Component owner=null;
	
	public ActionSaveTableAs(Component owner,JTable table)
		{
		super("Save As..");
		this.owner=owner;
		this.table=table;
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke ('S'));
		putValue(AbstractAction.LONG_DESCRIPTION,"Save As..");
		putValue(AbstractAction.SHORT_DESCRIPTION,"Save As..");
		}
	
	
	@Override
	public void actionPerformed(ActionEvent e)
			{
			TableModel m= table.getModel();
			JFileChooser chooser=new JFileChooser();
			if(chooser.showSaveDialog(this.owner)!= JFileChooser.APPROVE_OPTION) return; 
			File f= chooser.getSelectedFile();
			if(f.exists() &&
				JOptionPane.showConfirmDialog(owner, "Overwrite "+f+" exists. Overwrite ?")!=JOptionPane.OK_OPTION)
				{
				return;
				}
			try {
				PrintWriter out=new PrintWriter(new FileWriter(f));
				for(int i=0;i< m.getColumnCount();++i)
					{
					out.print(i==0?'#':'\t');
					out.print(m.getColumnName(i));
					}
				out.println();
				
				for(int j=0;j< m.getRowCount();++j)
				{
				for(int i=0;i< m.getColumnCount();++i)
					{
					if(i>0)out.print('\t');
					out.print(m.getValueAt(j,i));
					}
				out.println();
				}
				out.flush();
				out.close();
				} 
			catch (Exception e2)
				{
				JOptionPane.showMessageDialog(owner, e2.getMessage());
				}
		
		}
	}
